import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { TableBody } from '@/components/ui/table';
import { ResponsiveTable, ResponsiveTableHeader, ResponsiveTableRow, ResponsiveTableHead, ResponsiveTableCell, TableLoading, TableEmpty } from '@/components/ui/responsive-table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Progress } from '@/components/ui/progress';
import { Eye, Edit, Trash2, Search, Filter, Calendar, User, Clock } from 'lucide-react';

// 模拟任务数据
const mockTasks = [
  {
    id: 1,
    task_code: 'TASK-001',
    task_name: '需求分析',
    project_id: 1,
    project_name: '电商平台开发项目',
    description: '分析用户需求，制定功能规格说明书',
    assignee_name: '张三',
    participants: ['李四', '王五'],
    start_date: '2024-01-15',
    end_date: '2024-01-25',
    estimated_hours: 40,
    actual_hours: 35,
    status: '已完成',
    priority: '高',
    progress_percentage: 100,
    predecessor_tasks: [],
    successor_tasks: [2, 3]
  },
  {
    id: 2,
    task_code: 'TASK-002',
    task_name: '系统设计',
    project_id: 1,
    project_name: '电商平台开发项目',
    description: '设计系统架构和数据库结构',
    assignee_name: '李四',
    participants: ['张三', '赵六'],
    start_date: '2024-01-26',
    end_date: '2024-02-10',
    estimated_hours: 60,
    actual_hours: 45,
    status: '进行中',
    priority: '高',
    progress_percentage: 75,
    predecessor_tasks: [1],
    successor_tasks: [4, 5]
  },
  {
    id: 3,
    task_code: 'TASK-003',
    task_name: '前端开发',
    project_id: 1,
    project_name: '电商平台开发项目',
    description: '开发用户界面和交互功能',
    assignee_name: '王五',
    participants: ['钱七', '孙八'],
    start_date: '2024-02-11',
    end_date: '2024-03-15',
    estimated_hours: 120,
    actual_hours: 80,
    status: '进行中',
    priority: '中',
    progress_percentage: 65,
    predecessor_tasks: [1],
    successor_tasks: [6]
  },
  {
    id: 4,
    task_code: 'TASK-004',
    task_name: '后端开发',
    project_id: 1,
    project_name: '电商平台开发项目',
    description: '开发API接口和业务逻辑',
    assignee_name: '赵六',
    participants: ['李四', '钱七'],
    start_date: '2024-02-11',
    end_date: '2024-03-20',
    estimated_hours: 150,
    actual_hours: 100,
    status: '进行中',
    priority: '高',
    progress_percentage: 70,
    predecessor_tasks: [2],
    successor_tasks: [6]
  },
  {
    id: 5,
    task_code: 'TASK-005',
    task_name: '数据库设计',
    project_id: 1,
    project_name: '电商平台开发项目',
    description: '设计数据库表结构和关系',
    assignee_name: '李四',
    participants: ['张三'],
    start_date: '2024-01-26',
    end_date: '2024-02-05',
    estimated_hours: 30,
    actual_hours: 25,
    status: '已完成',
    priority: '中',
    progress_percentage: 100,
    predecessor_tasks: [1],
    successor_tasks: [4]
  }
];

const TaskList = ({ onEdit, onView, onDelete, projectId = null }) => {
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState('ALL');
  const [priorityFilter, setPriorityFilter] = useState('ALL');
  const [assigneeFilter, setAssigneeFilter] = useState('ALL');

  // 获取任务列表
  const fetchTasks = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      let filteredTasks = mockTasks;
      
      // 如果指定了项目ID，则只显示该项目的任务
      if (projectId) {
        filteredTasks = mockTasks.filter(task => task.project_id === parseInt(projectId));
      }
      
      setTasks(filteredTasks);
    } catch (error) {
      console.error('获取任务列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 过滤任务
  const filteredTasks = tasks.filter(task => {
    const matchesSearch = task.task_name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                         task.task_code.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                         task.description.toLowerCase().includes(searchKeyword.toLowerCase());
    const matchesStatus = statusFilter === 'ALL' || task.status === statusFilter;
    const matchesPriority = priorityFilter === 'ALL' || task.priority === priorityFilter;
    const matchesAssignee = assigneeFilter === 'ALL' || task.assignee_name === assigneeFilter;
    
    return matchesSearch && matchesStatus && matchesPriority && matchesAssignee;
  });

  // 获取状态徽章样式
  const getStatusBadgeVariant = (status) => {
    switch (status) {
      case '未开始': return 'secondary';
      case '进行中': return 'default';
      case '已完成': return 'success';
      case '已暂停': return 'destructive';
      case '已取消': return 'outline';
      default: return 'secondary';
    }
  };

  // 获取优先级徽章样式
  const getPriorityBadgeVariant = (priority) => {
    switch (priority) {
      case '高': return 'destructive';
      case '中': return 'default';
      case '低': return 'secondary';
      default: return 'secondary';
    }
  };

  // 计算任务延期状态
  const getTaskDelayStatus = (task) => {
    const today = new Date();
    const endDate = new Date(task.end_date);
    const isOverdue = today > endDate && task.status !== '已完成';
    const isDueSoon = today > new Date(endDate.getTime() - 3 * 24 * 60 * 60 * 1000) && 
                      today <= endDate && task.status !== '已完成';
    
    return { isOverdue, isDueSoon };
  };

  useEffect(() => {
    fetchTasks();
  }, [projectId]);

  return (
    <Card>
      <CardHeader>
        <CardTitle>任务列表</CardTitle>
      </CardHeader>
      <CardContent>
        {/* 搜索和筛选 */}
        <div className="flex flex-col sm:flex-row gap-4 mb-6">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground size-4" />
              <Input
                placeholder="搜索任务名称、编号或描述..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <div className="flex gap-2">
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部状态</SelectItem>
                <SelectItem value="未开始">未开始</SelectItem>
                <SelectItem value="进行中">进行中</SelectItem>
                <SelectItem value="已完成">已完成</SelectItem>
                <SelectItem value="已暂停">已暂停</SelectItem>
                <SelectItem value="已取消">已取消</SelectItem>
              </SelectContent>
            </Select>
            <Select value={priorityFilter} onValueChange={setPriorityFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="优先级" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部优先级</SelectItem>
                <SelectItem value="高">高</SelectItem>
                <SelectItem value="中">中</SelectItem>
                <SelectItem value="低">低</SelectItem>
              </SelectContent>
            </Select>
            <Select value={assigneeFilter} onValueChange={setAssigneeFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="负责人" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部负责人</SelectItem>
                {Array.from(new Set(tasks.map(task => task.assignee_name))).map(name => (
                  <SelectItem key={name} value={name}>{name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* 任务表格 */}
        <ResponsiveTable>
          <ResponsiveTableHeader>
            <ResponsiveTableRow>
              <ResponsiveTableHead width="24">任务编号</ResponsiveTableHead>
              <ResponsiveTableHead minWidth="32">任务名称</ResponsiveTableHead>
              <ResponsiveTableHead hideOnTablet minWidth="40">所属项目</ResponsiveTableHead>
              <ResponsiveTableHead width="20">负责人</ResponsiveTableHead>
              <ResponsiveTableHead width="20">状态</ResponsiveTableHead>
              <ResponsiveTableHead width="20">优先级</ResponsiveTableHead>
              <ResponsiveTableHead width="24">进度</ResponsiveTableHead>
              <ResponsiveTableHead hideOnMobile width="28">开始时间</ResponsiveTableHead>
              <ResponsiveTableHead hideOnMobile width="28">结束时间</ResponsiveTableHead>
              <ResponsiveTableHead hideOnTablet width="24">工时</ResponsiveTableHead>
              <ResponsiveTableHead width="24">操作</ResponsiveTableHead>
            </ResponsiveTableRow>
          </ResponsiveTableHeader>
          <TableBody>
            {loading ? (
              <TableLoading colSpan={11} />
            ) : filteredTasks.length === 0 ? (
              <TableEmpty colSpan={11} message="暂无任务数据" />
            ) : (
              filteredTasks.map(task => {
                const { isOverdue, isDueSoon } = getTaskDelayStatus(task);
                return (
                  <ResponsiveTableRow key={task.id} className={isOverdue ? 'bg-destructive/5' : ''}>
                    <ResponsiveTableCell className="font-mono text-sm" truncate title={task.task_code}>
                      {task.task_code}
                    </ResponsiveTableCell>
                    <ResponsiveTableCell className="font-medium">
                      <div className="flex items-center gap-2 min-w-0">
                        <span className="truncate" title={task.task_name}>
                          {task.task_name}
                        </span>
                        {isOverdue && (
                          <Badge variant="destructive" className="text-xs flex-shrink-0">
                            已延期
                          </Badge>
                        )}
                        {isDueSoon && !isOverdue && (
                          <Badge variant="default" className="text-xs flex-shrink-0">
                            即将到期
                          </Badge>
                        )}
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnTablet className="text-sm text-muted-foreground" truncate title={task.project_name}>
                      {task.project_name}
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <div className="flex items-center gap-1">
                        <User className="size-3 text-muted-foreground flex-shrink-0" />
                        <span className="truncate" title={task.assignee_name}>
                          {task.assignee_name}
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <Badge variant={getStatusBadgeVariant(task.status)} className="text-xs">
                        {task.status}
                      </Badge>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <Badge variant={getPriorityBadgeVariant(task.priority)} className="text-xs">
                        {task.priority}
                      </Badge>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <div className="flex items-center gap-2">
                        <div className="w-12 bg-secondary rounded-full h-2 flex-shrink-0">
                          <div 
                            className="bg-primary h-2 rounded-full transition-all"
                            style={{ width: `${task.progress_percentage}%` }}
                          />
                        </div>
                        <span className="text-xs text-muted-foreground flex-shrink-0">
                          {task.progress_percentage}%
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnMobile className="text-xs">
                      <div className="flex items-center gap-1">
                        <Calendar className="size-3 text-muted-foreground flex-shrink-0" />
                        <span className="truncate" title={task.start_date}>
                          {task.start_date}
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnMobile className="text-xs">
                      <div className="flex items-center gap-1">
                        <Calendar className="size-3 text-muted-foreground flex-shrink-0" />
                        <span className="truncate" title={task.end_date}>
                          {task.end_date}
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnTablet className="text-xs">
                      <div className="flex items-center gap-1">
                        <Clock className="size-3 text-muted-foreground flex-shrink-0" />
                        <span className="truncate" title={`${task.actual_hours}/${task.estimated_hours}h`}>
                          {task.actual_hours}/{task.estimated_hours}h
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <div className="flex items-center gap-1">
                        <Button 
                          variant="ghost" 
                          size="sm"
                          onClick={() => onView && onView(task)}
                          className="h-8 w-8 p-0"
                        >
                          <Eye className="size-3" />
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="sm"
                          onClick={() => onEdit && onEdit(task)}
                          className="h-8 w-8 p-0"
                        >
                          <Edit className="size-3" />
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="sm"
                          onClick={() => onDelete && onDelete(task)}
                          className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                        >
                          <Trash2 className="size-3" />
                        </Button>
                      </div>
                    </ResponsiveTableCell>
                  </ResponsiveTableRow>
                );
              })
            )}
          </TableBody>
        </ResponsiveTable>
      </CardContent>
    </Card>
  );
};

export default TaskList; 